<template>
    <div ref="container" class="fly-line-container"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { useFlyLine } from "./useFlyLine.js";
const container = ref(null);
let scene, camera, renderer, controls;
const { addTo, addFly, clear } = useFlyLine(); // 只拿工具，不立即用 scene

/* ========= 1. 生命周期 ========= */
onMounted(() => {
    initThree();
});
onUnmounted(() => {
    renderer?.dispose();
    clear();
});
/* ========= 2. 初始化 Three ========= */
function initThree() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(60, container.value.clientWidth / container.value.clientHeight, 0.1, 10000);
    camera.position.set(100, 100, 100);
    renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setSize(container.value.clientWidth, container.value.clientHeight);
    container.value.appendChild(renderer.domElement);
    controls = new OrbitControls(camera, renderer.domElement);
    // scene.add(new THREE.AxesHelper(5000)); // 是否显示坐标轴
    // 关键：等 scene 创建完再挂
    addTo(scene);
    // renderLines(); // 渲染初始飞线
    animate();
}

function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
}

/* ========= 3. 事件总线 ========= */
let startCbs = [];
let endCbs = [];

/* ========= 4. 对外暴露的三个接口 ========= */
/* 4-1 立即绘制一条飞线 */
function draw(id, from, to, color , glow = 3, speed = 1,radius = 1) {
    // 触发“开始”回调
    startCbs.forEach(cb => cb());
    // 调用底层 addFly
    addFly(scene, {
        color,
        glow,
        from, // 起始点
        to, // 终点
        width: 0, // 不再用 TubeGeometry，width 忽略
        headRatio: 0.08, // 让能量团更短
        maxScale: 4, // 最大球半径
        segments: 128, // 曲线分成 128 个球
        radius // 指定大小了
    });
    // 底层动画 2s / speed，结束后触发“结束”回调
    const duration = 3 / speed; //  底层动画 2s / speed，结束后触发“结束”回调
    setTimeout(() => endCbs.forEach(cb => cb(id)), duration * 1000);
}

/* 4-2 注册飞线出现回调 */
function onFlyStart(cb) {
    startCbs.push(cb);
}

/* 4-3 注册飞线结束回调 */
function onFlyEnd(cb) {
    endCbs.push(cb);
}

/* ========= 5. 把三个方法暴露给父组件 ========= */
defineExpose({ draw, onFlyStart, onFlyEnd });
</script>
<style lang="scss" scoped>
.fly-line-container {
    width: 100%;
    height: 100%;
    background-color: transparent;
}
</style>
